package com.syp.test.clustercacheflush.controller;

import java.util.Calendar;

import javax.ws.rs.POST;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.syp.test.clustercacheflush.builder.TaskBuilder;
import com.syp.test.clustercacheflush.domain.SettingsEntity;
import com.syp.test.clustercacheflush.domain.TaskEntity;
import com.syp.test.clustercacheflush.service.QuickTaskProcessService;
import com.syp.test.clustercacheflush.service.SettingsService;
import com.syp.test.clustercacheflush.util.ProcessResult;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequestMapping("/settings")
@Controller
public class SettingsController {

	@Autowired
	private SettingsService settingsService;
	@Autowired
	private TaskBuilder taskBuilder;
	@Autowired
	private QuickTaskProcessService quickTaskProcessService;

	@RequestMapping("/get")
	@POST
	@ResponseBody
	public SettingsEntity add(String key) {
		return this.settingsService.get(key);
	}

	@RequestMapping("/add")
	@POST
	@ResponseBody
	public ProcessResult add(@RequestBody SettingsEntity request) {
		ProcessResult pr = new ProcessResult();
		SettingsEntity setting = new SettingsEntity();
		setting.setKey(request.getKey());
		setting.setValue(request.getValue());
		setting.setCreateTime(Calendar.getInstance().getTime());
		setting.setLastUpdate(Calendar.getInstance().getTime());

		TaskEntity task = this.taskBuilder.buildClusterCacheSyncNotifyTask(setting);
		this.settingsService.save(setting, task);
		this.quickTaskProcessService.process(task);

		return pr;
	}

	@RequestMapping("/edit")
	@POST
	@ResponseBody
	public ProcessResult edit(@RequestBody SettingsEntity request) {
		ProcessResult pr = new ProcessResult();

		log.info("修改配置参数请求入参：{}", JSON.toJSONString(request));
		SettingsEntity setting = this.settingsService.get(request.getKey());
		setting.setValue(request.getValue());
		setting.setLastUpdate(Calendar.getInstance().getTime());

		TaskEntity task = this.taskBuilder.buildClusterCacheSyncNotifyTask(setting);
		this.settingsService.save(setting, task);
		this.quickTaskProcessService.process(task);

		log.info("修改配置参数请求出参：{}", JSON.toJSONString(pr));

		return pr;
	}
}
